<script setup lang="ts">
import YkPagination from '@yk/components/pagination/YkPagination.vue'
import { Pages } from '@typings/pages'
import YkTableColumn from '@yk/components/table-column/YkTableColumn.vue'
import { ElForm, ElTable } from 'element-plus'
import { MountedCheck } from '@/utils'
import { TableUtil } from '@utils/table-util'
import YkDatePicker from '@yk/components/date-picker/YkDatePicker.vue'
import { getDeviceListAPI } from '@/api/device'
import { DeviceDTO } from '@/api/entity/device'
import { deleteDeviceHistoryByDateAPI, getDeviceHistoryByDateAPI } from '@/api/history'
import { ObjectUtil } from '@utils/object-util'

defineOptions({ name: 'RemoveHistoricalData' })
const route = useRoute()

const mc = new MountedCheck()
onMounted(async () => {
  getDeviceList()
  mc.end()
})

onActivated(() => {
  // if (mc.isMounted()) return
  tableDataRef.value.doLayout()
})

// region TODO 设备
const deviceList = shallowRef<DeviceDTO[]>([])
function getDeviceList () {
  getDeviceListAPI().then((res) => {
    res.result().then((rdata) => {
      deviceList.value = rdata.data
    })
  })
}
// endregion

// region TODO 查询
const searchParams = reactive({
  // 结束时间
  endTime: '',
  // 开始时间
  startTime: '',
  // 设备主键id
  tableName: ''
})
const exportParams = ref()
function searchHandle () {
  pages.pageNum = 1
  exportParams.value = ObjectUtil.copy(searchParams)
  getTableData()
}
// endregion

// function rabbitPopulation (month) { // 40
//   const monthCount = []
//   const rabbitList = [{ age: 0 }]
//   for (let i = 0; i < month; i++) {
//     for (let j = 0, len = rabbitList.length; j < len; j++) {
//       rabbitList[j].age++
//       if (rabbitList[j].age >= 3) rabbitList.push({ age: 1 })
//     }
//     monthCount.push(rabbitList.length)
//   }
//   return { sumCount: rabbitList.length, monthCount }
// }

// function rabbitPopulation (month) { // 1476
//   const monthCount = []
//   const rabbitList = [1, 0, 0, 0]
//   for (let i = 0; i < month; i++) {
//     for (let j = 3; j > 0; j--) {
//       rabbitList[j] = rabbitList[j] += rabbitList[j - 1]
//       rabbitList[j - 1] = 0
//     }
//     rabbitList[1] = rabbitList[1] += rabbitList[3]
//     monthCount.push(rabbitList[1] + rabbitList[2] + rabbitList[3])
//   }
//   return { sumCount: monthCount[monthCount.length - 1], monthCount }
// }

// function rabbitPopulation (month) {
//   const monthCount = []
//   let sumCount = 1n
//   const rabbitList = [1n, 0n, 0n, 0n]
//   for (let i = 0; i < month; i++) {
//     for (let j = 3; j > 0; j--) {
//       rabbitList[j] = rabbitList[j] += rabbitList[j - 1]
//       rabbitList[j - 1] = 0n
//     }
//     rabbitList[1] += rabbitList[3]
//     sumCount += rabbitList[3]
//     monthCount.push(sumCount)
//   }
//   return { sumCount: monthCount[monthCount.length - 1], monthCount }
// }

// region TODO 表格数据
const pages = reactive(new Pages())
const tableDataRef = shallowRef<InstanceType<typeof ElTable>>()
const tableData = shallowRef<any[]>([])
const tableHeader = shallowRef<{ prop: string, title: string }[]>([])
function getTableData () {
  if (!searchParams.tableName) {
    ElMessage.info('请选择一个设备')
    return
  }
  const loading = ElLoading.service()
  getDeviceHistoryByDateAPI({
    ...pages.getParams(),
    param: searchParams
  }).then((res) => {
    res.result().then((rdata) => {
      const data = rdata.records || []
      let _tableHeader = null
      const _tableData = []
      data.forEach(item => {
        if (!_tableHeader) {
          _tableHeader = []
          item.variableVOList.forEach(item => {
            _tableHeader.push({ prop: item.variableId, title: item.name + (item.unit ? `（${item.unit}）` : '') })
          })
          tableHeader.value = _tableHeader
        }
        const _tableItem = { ts: item.ts }
        item.variableVOList.forEach(item1 => {
          _tableItem[item1.variableId] = item1.value
        })
        _tableData.push(_tableItem)
      })
      tableData.value = _tableData
      pages.total = rdata.total
    })
  }).finally(loading.close)
}
// endregion

// region TODO 删除条件内数据
function delParamsTableData () {
  if (!exportParams.value?.tableName) {
    ElMessage.info('请选择一个设备')
    return
  }
  delHistoricalTableData(exportParams.value)
}
// endregion

// region TODO 删除更多数据
const delDataParams = ref({
  // 结束时间
  endTime: '',
  // 开始时间
  startTime: ''
})
const delMoreDataDialogModel = ref(false)
function showDelMoreDataDialog () {
  if (!searchParams?.tableName) {
    ElMessage.info('请选择一个设备')
    return
  }
  delMoreDataDialogModel.value = true
}
function closeDelMoreDataDialog () {
  delMoreDataDialogModel.value = false
}
function delMoreDataHandle () {
  delHistoricalTableData({
    tableName: searchParams.tableName,
    ...delDataParams.value
  })
  closeDelMoreDataDialog()
}
// endregion

// region TODO 删除数据
type DelDataParamsType = Parameters<typeof deleteDeviceHistoryByDateAPI>[0]
function delHistoricalTableData (delDataParams: DelDataParamsType) {
  dangerConfirmOptions.value = {
    message: '确认删除这些数据，删除后无法恢复',
    verifyStr: '删除数据',
    successCallback () {
      const loading = ElLoading.service()
      deleteDeviceHistoryByDateAPI(delDataParams).then((res) => {
        res.result().then(() => {
          ElMessage.success('删除成功')
          getTableData()
        })
      }).finally(loading.close)
    }
  }
  showDangerConfirmDialog()
}
// endregion

// region TODO 高危操作确认
const dangerConfirmOptions = ref({
  message: '',
  verifyStr: '',
  successCallback: null as {()}
})
const verifyValue = ref()
const dangerConfirmDialogModel = ref(false)
function showDangerConfirmDialog () {
  verifyValue.value = ''
  dangerConfirmDialogModel.value = true
}
function submitDangerConfirmHandle () {
  if (dangerConfirmOptions.value.verifyStr !== verifyValue.value) {
    ElMessage.error('验证信息不一致')
    return
  }
  dangerConfirmDialogModel.value = false
  dangerConfirmOptions.value.successCallback()
}
// endregion

</script>

<template>
  <div class="layout_view d-flex" style="min-height: 100%">
    <div class="c_card-page w-100">
      <div class="c_card_header c_card-title bor-divider-b">数据清理</div>
      <!--搜索表单-->
      <el-form inline class="c_form-search pt-16" @submit.prevent="searchHandle">
        <el-form-item label="查询">
          <el-select v-model="searchParams.tableName" placeholder="请选择设备">
            <el-option v-for="item in deviceList" :key="item.id" :label="item.deviceName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <yk-date-picker
            v-model:start="searchParams.startTime" v-model:end="searchParams.endTime" type="daterange"
            :shortcuts="[-60, -30, -7, -3, 0]" value-format="YYYY-MM-DD HH:mm:ss" :default-date="30"
            :days="60"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchHandle">查询</el-button>
          <el-dropdown
            split-button type="danger"
            class="ml-12"
            @click="delParamsTableData"
          >
            移除条件内数据
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item class="color-danger" @click="showDelMoreDataDialog">移除更多数据</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </el-form-item>
      </el-form>
      <div />
      <!--表格-->
      <el-table ref="tableDataRef" class="c_table-page w-100" stripe :data="tableData">
        <el-table-column label="#" type="index" fixed :index="TableUtil.indexMethod.bind(null, pages)" />
        <yk-table-column label="数据时间" prop="ts" fixed />
        <yk-table-column
          v-for="item in tableHeader" :key="item.prop" :label="item.title"
          :prop="item.prop"
          width=""
        />
      </el-table>
      <!--分页-->
      <el-affix target=".c_table-page" position="bottom" :offset="0">
        <yk-pagination class="c_table-pagination-page" :pages="pages" @handle="getTableData" />
      </el-affix>
    </div>
    <!--删除更多数据-->
    <el-dialog v-model="delMoreDataDialogModel" title="删除更多数据" width="350px">
      <el-form style="margin: -12px 0;">
        <el-form-item label="删除范围">
          <yk-date-picker
            v-model:start="delDataParams.startTime" v-model:end="delDataParams.endTime" type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-date="30"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button size="default" @click="closeDelMoreDataDialog">取消</el-button>
        <el-button type="primary" size="default" @click="delMoreDataHandle">确认</el-button>
      </template>
    </el-dialog>
    <!--高危操作确认 - 只作确认功能，可复用-->
    <el-dialog
      v-model="dangerConfirmDialogModel" title="操作确认" width="450px"
      :close-on-click-modal="false"
      draggable
    >
      <div style="margin-top: -16px;">
        <p class="mb-1">你当前的操作存在一些风险</p>
        <p class="mb-1">{{ dangerConfirmOptions.message }}</p>
        <p>请在文本框中输入<el-tag type="danger">{{ dangerConfirmOptions.verifyStr }}</el-tag>确认操作</p>
        <div class="d-flex mt-2">
          <el-input v-model.trim="verifyValue" />
          <el-button type="primary" class="ml-2" @click="submitDangerConfirmHandle">确认</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
</style>
